//package com.infra.server.utils;
//
//import cn.hutool.core.util.ObjectUtil;
//import cn.hutool.core.util.StrUtil;
//import com.alibaba.fastjson.JSONObject;
//import lombok.extern.slf4j.Slf4j;
//import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
//import org.elasticsearch.action.bulk.BulkRequest;
//import org.elasticsearch.action.bulk.BulkResponse;
//import org.elasticsearch.action.delete.DeleteRequest;
//import org.elasticsearch.action.delete.DeleteResponse;
//import org.elasticsearch.action.get.GetRequest;
//import org.elasticsearch.action.get.GetResponse;
//import org.elasticsearch.action.index.IndexRequest;
//import org.elasticsearch.action.index.IndexResponse;
//import org.elasticsearch.action.search.SearchRequest;
//import org.elasticsearch.action.search.SearchResponse;
//import org.elasticsearch.action.support.master.AcknowledgedResponse;
//import org.elasticsearch.action.update.UpdateRequest;
//import org.elasticsearch.action.update.UpdateResponse;
//import org.elasticsearch.client.RequestOptions;
//import org.elasticsearch.client.RestHighLevelClient;
//import org.elasticsearch.client.indices.CreateIndexRequest;
//import org.elasticsearch.client.indices.CreateIndexResponse;
//import org.elasticsearch.client.indices.GetIndexRequest;
//import org.elasticsearch.common.xcontent.XContentBuilder;
//import org.elasticsearch.common.xcontent.XContentType;
//import org.elasticsearch.core.TimeValue;
//import org.elasticsearch.rest.RestStatus;
//import org.elasticsearch.search.SearchHit;
//import org.elasticsearch.search.SearchHits;
//import org.elasticsearch.search.aggregations.Aggregations;
//import org.elasticsearch.search.builder.SearchSourceBuilder;
//import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.stereotype.Component;
//
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Map;
//
///**
// * @author win
// * @date 2021/7/21 17:52
// * elasticsearch工具类
// * es搜索参考：https://blog.51cto.com/u_12302929/3294429
// */
//@Slf4j
//@Component
//public class EsUtil {
//
//    @Qualifier("client")
//    @Autowired
//    private RestHighLevelClient client;
//
////    public static String scheme = "http";
////    public static String host = "localhost";
////    public static int port = 9200;
////    public static String username = "elastic";
////    public static String password = "elastic";
////    public static int connTimeout = 3000;
////    public static int socketTimeout = 5000;
////    public static int connectionRequestTimeout = 1000;
////
////    private static RestHighLevelClient client;
//
////    /**
////     * 创建连接
////     */
////    public static synchronized RestHighLevelClient makeConnection() {
////        if (client == null) {
////            log.info("----------创建es连接----------");
////            // 用户认证对象
////            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
////            // 设置用户密码
////            credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(username,password));
////
////            RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(host,port,scheme));
////            // 设置允许修改默认请求配置的回调
////            restClientBuilder.setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder
////                    .setConnectionRequestTimeout(connectionRequestTimeout)
////                    .setSocketTimeout(socketTimeout)
////                    .setConnectTimeout(connTimeout))
////                    .setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
////
////            client = new RestHighLevelClient(restClientBuilder);
////        }
////        return client;
////    }
////
////    /**
////     * 关闭连接
////     */
////    public static synchronized void closeConnection() throws IOException {
////        log.info("----------关闭es连接----------");
////        client.close();
////        client = null;
////    }
//
//    /**
//     * 添加索引
//     */
//    public synchronized boolean createIndex(String index, XContentBuilder xContentBuilder) throws IOException {
//        try {
//            CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);
//            if (ObjectUtil.isNotEmpty(xContentBuilder)) {
//                createIndexRequest.mapping(xContentBuilder);
//            }
//            // 先判断索引是否存在，然后在执行是否 添加指令
//            if (!existIndex(index)) {
//                CreateIndexResponse response = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
//                return response.isAcknowledged();
//            }
//        } catch (IOException e) {
//            log.error("添加索引异常： {}", e.getMessage());
//        }
//        return false;
//    }
//
//    /**
//     * 判断索引是否存在
//     */
//    public boolean existIndex(String index) {
//        boolean exists = false;
//        try {
//            GetIndexRequest getIndexRequest = new GetIndexRequest(index);
//            exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
//        } catch (IOException e) {
//            log.error("判断索引是否存在异常  {}", e.getMessage());
//        }
//        return exists;
//    }
//
//    /**
//     * 删除索引
//     */
//    public boolean delIndex(String index) {
//        try {
//            if (existIndex(index)) {
//                DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
//                AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
//                if (delete.isAcknowledged()) {
//                    return true;
//                }
//            }
//        } catch (IOException e) {
//            log.error("删除索引异常: {}", e.getMessage());
//        }
//        return false;
//    }
//
//    /**
//     * 插入数据
//     *
//     * @param index   索引名称
//     * @param id      文档id
//     * @param jsonStr json数据
//     */
//    public boolean insertDocument(String index, String id, String jsonStr) {
//        try {
//            //组装数据 创建请求
//            IndexRequest request = new IndexRequest(index);
//            // 设置规则
//            request.timeout(TimeValue.timeValueSeconds(1));
//            if (StrUtil.isNotEmpty(id)) {
//                request.id(id);
//            }
//            // 将数据放入请求对象里面
//            request.source(jsonStr, XContentType.JSON);
//            IndexResponse response = client.index(request, RequestOptions.DEFAULT);
//            RestStatus status = response.status();
//            if (status.equals(RestStatus.OK) || status.equals(RestStatus.CREATED)) {
//                return true;
//            }
//        } catch (IOException e) {
//            log.error("插入文档异常：{}", e.getMessage());
//        }
//        return false;
//    }
//
//    /**
//     * 判断文档是否存在
//     *
//     * @param index 索引名称
//     * @param id    文档id
//     */
//    public boolean existDocument(String index, String id) {
//        boolean exists = false;
//        try {
//            GetRequest request = new GetRequest(index, id);
//            //禁用fetching _source
//            request.fetchSourceContext(new FetchSourceContext(false));
//            request.storedFields("_none_");
//            exists = client.exists(request, RequestOptions.DEFAULT);
//        } catch (IOException e) {
//            log.error("判断文档是否存在异常： {}", e.getMessage());
//        }
//        return exists;
//    }
//
//    /**
//     * 更新文档信息
//     *
//     * @param index   索引
//     * @param id      文档id
//     * @param jsonStr 数据
//     */
//    public boolean updateDocument(String index, String id, String jsonStr) {
//        try {
//            UpdateRequest request = new UpdateRequest(index, id).doc(jsonStr, XContentType.JSON);
//            UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
//            RestStatus status = response.status();
//            if (status.equals(RestStatus.OK)) {
//                return true;
//            }
//        } catch (IOException e) {
//            log.error("更新文档异常：{}", e.getMessage());
//        }
//        return false;
//    }
//
//    /**
//     * 根据id获取文档
//     *
//     * @param index 索引名称
//     * @param id    文档id
//     * @return
//     */
//    public Map<String, Object> getDocument(String index, String id) {
//        GetRequest request = new GetRequest(index, id);
//        try {
//            GetResponse documentFields = client.get(request, RequestOptions.DEFAULT);
//            return documentFields.getSourceAsMap();
//        } catch (IOException e) {
//            log.error("获取文档异常: {}", e.getMessage());
//        }
//        return null;
//    }
//
//    /**
//     * 删除文档
//     *
//     * @param index 索引名称
//     * @param id    文档id
//     */
//    public boolean delDocument(String index, String id) {
//        try {
//            DeleteRequest request = new DeleteRequest(index, id);
//            DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);
//            if (delete.status().equals(RestStatus.OK)) {
//                return true;
//            }
//        } catch (IOException e) {
//            log.error("删除文档异常: {}", e.getMessage());
//        }
//        return false;
//    }
//
//    /**
//     * 批量插入数据
//     *
//     * @param index   索引
//     * @param list    批量文档
//     * @param timeout 超时时间，单位秒
//     */
//    public boolean batchDocument(String index, List<Object> list, Long timeout) {
//        try {
//            BulkRequest bulkRequest = new BulkRequest(index);
//            if (ObjectUtil.isNotEmpty(timeout)) {
//                bulkRequest.timeout(TimeValue.timeValueSeconds(timeout));
//            }
//            if (ObjectUtil.isNotEmpty(list)) {
//                list.forEach(item -> bulkRequest.add(new IndexRequest().source(JSONObject.toJSONString(item), XContentType.JSON)));
//                BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
//                if (response.status().equals(RestStatus.OK)) {
//                    return true;
//                }
//            }
//        } catch (IOException e) {
//            log.error("批量插入文档数据异常: {}", e.getMessage());
//        }
//        return false;
//    }
//
//    /**
//     * 查询
//     * 搜索分页，能够经过from size组合来进行。from表示从第几行开始，size表示查询多少条文档。from默认为0，size默认为10
//     * size不能超过max_result_window参数的值（默认10000条）
//     *
//     * @param index         索引
//     * @param sourceBuilder 搜索条件
//     */
//    public List<Map<String, Object>> searchDocument(String index, SearchSourceBuilder sourceBuilder) {
//        try {
//            SearchRequest request = new SearchRequest(index);
//            if (ObjectUtil.isNotEmpty(sourceBuilder)) {
//                // 返回实际命中数，官方默认10000条
//                sourceBuilder.trackTotalHits(true);
//                request.source(sourceBuilder);
//            }
//            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//            if (response.status().equals(RestStatus.OK)) {
//                SearchHits hits = response.getHits();
//                List<Map<String, Object>> mapList = new ArrayList<>();
//                if (hits != null) {
//                    for (SearchHit hit : hits) {
//                        mapList.add(hit.getSourceAsMap());
//                    }
//                }
//                return mapList;
//            }
//        } catch (IOException e) {
//            log.error("查询数据异常：{}", e.getMessage());
//        }
//        return null;
//    }
//
//    /**
//     * 聚合查询
//     */
//    public Aggregations aggregateQuery(String index,SearchSourceBuilder sourceBuilder) {
//        try {
//            SearchRequest request = new SearchRequest(index);
//            request.source(sourceBuilder);
//            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//            if (response.status().equals(RestStatus.OK)) {
//                return response.getAggregations();
//            }
//        } catch (IOException e) {
//            log.error("聚合查询异常：{}",e.getMessage());
//        }
//        return null;
//    }
//}
